package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.hst.ThreeDesUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONObject
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat
import java.time.Instant
import cn.com.kh.getProperty;

/**
 *
 * @Title: autoHSTreallocation
 * @Description:华盛通名单重新分配 页面ID：DZ9S48        hst_listallocation_bacth 导入批次表         marketing_temporary 导入详情表
 * @author: 陶豪* @date 2021-10-22 10:22:00
 *
 */

public class autoHSTreallocation implements ServiceBackInvoke {

    private static final Logger log = LoggerFactory.getLogger(autoHSTreallocation.class);
    String inData = "";
    String outData = "";


    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = httpServletRequest.getMethod();
        String Batch_id = "";
        String Interface_type = "";
        String dataSourceID = "dataSource";

        //查询有没有处理中的批次  0是处理中 1是已完成 2是名单导入  3暂停
        try {
            def batchnumList = eliteBean.chaxun_sql("select batch_id, Interface_type From hst_listallocation_bacth Where batch_state = '0' and handler_State = 0 order by createddate desc ", "dataSource");
            log.debug("有多少个批次:" + batchnumList.size());
            if (batchnumList.size() > 0) {
                Map batchnumMap = batchnumList.get(0);
                Batch_id = batchnumMap.get("batch_id");//批次id
                Interface_type = batchnumMap.get("Interface_type");//接口模式 1是 2 否

                //查询导入详情表
                List marktingList = eliteBean.chaxun_sql("Select distinct batch_id, hsid, counselor_id, objective_guid, staff_id, rolegroup_id From marketing_temporary where 1 = 1 and state is null and batch_id='" + Batch_id + "'", "dataSource");
                eliteBean.update("Update hst_listallocation_bacth Set batch_state=1 where batch_id='" + Batch_id + "' ", "dataSource");

                log.debug(marktingList.size() + "=======：详情marktingList.size()")
                for (int i = 0; i < marktingList.size(); i++) {

                    long startTime = System.currentTimeMillis();
                    Map marktingMap = marktingList.get(i);
                    String hsid = marktingMap.get("hsid");//华盛号
                    Batch_id = marktingMap.get("batch_id");//批次ID
                    String Staff_id = marktingMap.get("staff_id");//人员ID
                    String Rolegroup_Id = marktingMap.get("rolegroup_id");//人员组别
                    String counselor_id = marktingMap.get("counselor_id");//服务顾问ID

                    // 查询名单是否已经存在
                    def custCountList = eliteBean.chaxun_sql("Select Customer_Guid, registerstatus From Customer Where Customer_Id = '" + hsid + "'", "dataSource");
                    log.debug(custCountList.size() + "=======：客户是否存在custCountList.size()");
                    //判断客户是否存在
                    if (custCountList.size() > 0) {
                        log.debug(custCountList.get(0).get("Customer_Guid"));
                        String Customer_Guid = custCountList.get(0).get("Customer_Guid");
                        String registerstatus = custCountList.get(0).get("registerstatus");
                        def isrepeat = eliteBean.chaxun_sql("select HANDLEBY_ID, OBJECTIVE_GUID, HANDLEGROUP_ID, DISTRIBUTIONNUMBER from objective where MAP_ID='MY48ZX' and customer_guid= '" + Customer_Guid + "'", "dataSource");

                        //判断该客户是否有任务
                        log.debug(isrepeat.size() + "=======：客户是否有任务");
                        if (isrepeat.size() <= 0) {
                            eliteBean.update("Update marketing_temporary Set state=2, result_desc='No task page' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                        } else {
                            String HANDLEBY_ID = isrepeat.get(0).get("HANDLEBY_ID");//获取当前处理人
                            String HANDLEGROUP_ID = isrepeat.get(0).get("HANDLEGROUP_ID");//获取当前处理组
                            String Objective_Guid = isrepeat.get(0).get("OBJECTIVE_GUID");//obj GUID

                            //分配累计数
                            String DISTRIBUTION_NUMBER_STR = isrepeat.get(0).get("DISTRIBUTIONNUMBER");
                            Integer DISTRIBUTION_NUMBER = 1;

                            if(DISTRIBUTION_NUMBER_STR == null || DISTRIBUTION_NUMBER_STR == 0 ){
                                DISTRIBUTION_NUMBER = 1;
                            }else{
                                DISTRIBUTION_NUMBER = Integer.parseInt(DISTRIBUTION_NUMBER_STR);
                            }

                            log.debug("判断需要绑定的顾问（"+ Staff_id +"）与原顾问（"+HANDLEBY_ID+"）是否一致；判断需要绑定的顾问（"+counselor_id+"）是否是空");
                            if (HANDLEBY_ID.equals(Staff_id)) {//判断需要绑定的顾问与原顾问是否一致
                                eliteBean.update("Update marketing_temporary Set state=2, result_desc='Consistent with the original consultant' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                            }else if(counselor_id == "" || counselor_id == null){//判断需要绑定的顾问是否是空，为空则回到公海池
                                boolean isflag = dealBindCustTOStaff(hsid, counselor_id, 2, DISTRIBUTION_NUMBER);
                                //判断解绑定成功,成功则修改表
                                if (isflag == true) {
                                    //修改assign_his 表
                                    eliteBean.update("INSERT INTO assign_his (ASSIGN_GUID, CUSTOMER_GUID, OBJECTIVE_GUID, OLDHANDLEGROUP_ID, OLDHANDLEBY_ID, NEWHANDLEGROUP_ID, NEWHANDLEBY_ID, ASSIGNGROUP_ID, ASSIGNBY_ID, ASSIGNDATE, RETURNGROUP_ID, RETURNBY_ID, RETURNFLAG, SUCCESS_GUID) VALUES (UUID(), '" + Customer_Guid + "', '" + Objective_Guid + "', '" + HANDLEGROUP_ID + "', '" + HANDLEBY_ID + "', '', '', 'SYSTEM', 'SELITE', NOW(), '', '', '0', '顾问为空，回到公海池' )", "dataSource");
                                    //修改Objective 表
                                    eliteBean.update("UPDATE Objective SET Handlegroup_Id = '', Handleby_Id = '', recycledate = null, retaindeadline = null, objectivesubstatus='OPEN', contact_cause = null WHERE Objective_Guid = '" + Objective_Guid + "' AND MAP_ID = 'MY48ZX'", "dataSource");
                                    //修改elitetask 表
                                    eliteBean.update("Update Elitetask Set Handlegroup_Id='', Handleby_Id='', CREATEDDATE=now(), objectivesubstatus='OPEN', MODIFIEDDATE=null Where Objective_Guid = '" + Objective_Guid + "' and MAP_ID='MY48ZX'", "dataSource");
                                    //修改marketing_temporary 表
                                    eliteBean.update("Update marketing_temporary Set state=1, result_desc='Advisor is empty, return  public pool' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                                    log.debug("回收到公海池成功！")
                                } else {
                                    eliteBean.update("Update marketing_temporary Set state=2, result_desc='Interface handling exception' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                                    log.debug("回收到公海池失败！")
                                }

                            } else {
                                //接口规则 1是 2否
                                log.debug("接口规则（"+ Interface_type);
								if (Interface_type=="2") {
                                    eliteBean.update("INSERT INTO assign_his (ASSIGN_GUID, CUSTOMER_GUID, OBJECTIVE_GUID, OLDHANDLEGROUP_ID, OLDHANDLEBY_ID, NEWHANDLEGROUP_ID, NEWHANDLEBY_ID, ASSIGNGROUP_ID, ASSIGNBY_ID, ASSIGNDATE, RETURNGROUP_ID, RETURNBY_ID, RETURNFLAG, SUCCESS_GUID)VALUES (UUID(), '" + Customer_Guid + "', '" + Objective_Guid + "', '" + HANDLEGROUP_ID + "', '" + HANDLEBY_ID + "', '" + Rolegroup_Id + "', '" + Staff_id + "', 'SYSTEM', 'SELITE', NOW(), '', '', '0', 'Service consultant reassignment' )", "dataSource");
                                    //修改Objective 表
                                    log.debug("hsid:" + hsid);
                                    eliteBean.update("Update Objective Set distributiontime = case when Handlegroup_Id is null or Handlegroup_Id = '' then now() else distributiontime end, distributionnumber=case when Handlegroup_Id is null or Handlegroup_Id='' then distributionnumber+1 else distributionnumber end, Handlegroup_Id='" + Rolegroup_Id + "', Handleby_Id='" + Staff_id + "', recycledate = null, retaindeadline = null, objectivesubstatus='OPEN', contact_cause = null Where Objective_Guid =  '" + Objective_Guid + "' and MAP_ID='MY48ZX'", "dataSource");
                                    //修改elitetask 表
                                    eliteBean.update("Update Elitetask Set Handlegroup_Id='" + Rolegroup_Id + "', Handleby_Id='" + Staff_id + "', CREATEDDATE=now(), objectivesubstatus='OPEN', contact_cause = null Where Objective_Guid = '" + Objective_Guid + "' and MAP_ID='MY48ZX'", "dataSource");
                                    //分配成功 则修改批次表 成功数+1
                                    //eliteBean.update("Update hst_listallocation_bacth Set  succeed_num=succeed_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                                    eliteBean.update("Update marketing_temporary Set state=1, result_desc ='Non interface mode, successful replacement of service advisor！' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                                    log.debug("非接口模式，更换服务顾问成功！")

                                } else {
                                    boolean isflag;
                                    if(HANDLEBY_ID =="" || HANDLEBY_ID ==null){//分配，原顾问为空
                                         isflag = dealBindCustTOStaff(hsid, counselor_id, 0, DISTRIBUTION_NUMBER);
                                    }else{//调整
                                         isflag = dealBindCustTOStaff(hsid, counselor_id, 1, DISTRIBUTION_NUMBER);
                                    }
                                    //判断是否绑定成功  成功则修改表
                                    if (isflag == true) {
                                        eliteBean.update("INSERT INTO assign_his (ASSIGN_GUID, CUSTOMER_GUID, OBJECTIVE_GUID, OLDHANDLEGROUP_ID, OLDHANDLEBY_ID, NEWHANDLEGROUP_ID, NEWHANDLEBY_ID, ASSIGNGROUP_ID, ASSIGNBY_ID, ASSIGNDATE, RETURNGROUP_ID, RETURNBY_ID, RETURNFLAG, SUCCESS_GUID) VALUES (UUID(), '" + Customer_Guid + "', '" + Objective_Guid + "', '" + HANDLEGROUP_ID + "', '" + HANDLEBY_ID + "', '" + Rolegroup_Id + "', '" + Staff_id + "', 'SYSTEM', 'SELITE', NOW(), '', '', '0', '服务顾问重新分配' )", "dataSource");
                                        //修改Objective 表
                                        log.debug("hsid:" + hsid);
                                        eliteBean.update("Update Objective set distributiontime = case when Handlegroup_Id is null or Handlegroup_Id='' then now() else distributiontime end, distributionnumber=case when Handlegroup_Id is null or Handlegroup_Id='' then distributionnumber+1 else distributionnumber end, Handlegroup_Id='" + Rolegroup_Id + "', Handleby_Id='" + Staff_id + "', recycledate = null, retaindeadline = null, objectivesubstatus='OPEN', contact_cause = null Where Objective_Guid =  '" + Objective_Guid + "' and MAP_ID='MY48ZX' ", "dataSource");
                                        //修改elitetask 表
                                        eliteBean.update("Update Elitetask Set Handlegroup_Id='" + Rolegroup_Id + "', Handleby_Id='" + Staff_id + "', CREATEDDATE=now(), objectivesubstatus='OPEN', MODIFIEDDATE=null Where Objective_Guid = '" + Objective_Guid + "' and MAP_ID='MY48ZX'", "dataSource");
                                        //分配成功 则修改批次表 成功数+1
                                        //eliteBean.update("Update hst_listallocation_bacth Set succeed_num=succeed_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                                        eliteBean.update("Update marketing_temporary Set state=1,result_desc ='' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                                        log.debug("分配成功！")
                                    } else {
                                        //否则 失败数+1
                                        //eliteBean.update("Update hst_listallocation_bacth Set  lose_num=lose_num+1 where batch_id='" + Batch_id + "' ", "dataSource");
                                        eliteBean.update("Update marketing_temporary Set state=2, result_desc='Interface handling exception' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                                        log.debug("分配失败！")
                                    }
                                 }
                            }
                        }
                    } else {
                        eliteBean.update("Update marketing_temporary Set state=2, result_desc='platform system does not have this data' where hsid='" + hsid + "' and batch_id='" + Batch_id + "' ", "dataSource");
                        //eliteBean.update("Update hst_listallocation_bacth Set  lose_num=lose_num+1 where batch_id='" + Batch_id + "'  ", "dataSource");
                    }
                }

                // 查询累计成功 succeed_num/失败数 lose_num
                def succeed_num,lose_num=0;
                def numCountList = eliteBean.chaxun_sql("Select sum(case when state=1 then 1 else 0 end) as succeed_num, sum(case when state=2 then 1 else 0 end) as lose_num From marketing_temporary Where batch_id = '" + Batch_id + "'", "dataSource");
                //判断客户是否存在
                if (numCountList.size() > 0) {
                    succeed_num= numCountList.get(0).get("succeed_num");
                    lose_num= numCountList.get(0).get("lose_num");
                    log.debug("succeed_num:"+succeed_num+"  lose_num:"+lose_num);
                }
                //分配完成后 将批次状态改成1 已完成
                eliteBean.update("Update hst_listallocation_bacth Set batch_state='1', succeed_num='" + succeed_num + "', lose_num='" + lose_num + "' where batch_id='" + Batch_id + "' ", "dataSource");
            }
            outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
            //修改详情表 将失败的信息插入到详情表
            eliteBean.update("Update marketing_temporary Set result_code='-1', result_desc='" + e.getMessage() + "' where batch_id='" + Batch_id + "' ", "dataSource");
        }
        //修改详情表 将成功的信息插入到详情表

        return outData
    }

    /**
     * 调用接口同步华盛内部系统服务顾问绑定
     * @param eliteBean
     * @param Customerid
     * @param r_Rolegroup_Id
     * @param r_Staff_Id
     * @return
     */
    public static boolean dealBindCustTOStaff(String Customerid, String r_Loginname, Integer DivideType, Integer DivideNumber ) {
        boolean reFlag = true;
        log.debug("绑定接口");
        try {
            //华盛接口连续调用可能异常 添加1S睡眠
            Thread.sleep(1 * 1000);
            String injson = "{\"hsNo\":\"" + Customerid + "\",\"managerId\":\"" + r_Loginname + "\",\"divideType\":\"" + DivideType +"\",\"divideNumber\":\""+ DivideNumber +"\"}";
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json");
            def sysurl = getProperty.get("crmurl");//配置本地接口地址
            sysurl = sysurl + "aipHSTBindCounselor";
            def getResult = Util.doHttpPostUseHead(sysurl, injson, "UTF-8", 100000, 0, headMap);
            log.debug("绑定接口返回：" + getResult);
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "result");
            log.debug("绑定接口返回code：" + code);
            if (code == "1") {
                reFlag = true;
            } else {
                reFlag = false;
            }
        } catch (Exception e) {
            log.error("绑定客户异常!", e);
            reFlag = false;
        }
        log.debug("reFlag：" + reFlag);
        return reFlag;
    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;

    }


}